<template xlang="wxml" minapp="mpvue">
	<view class="tki-qrcode">
		<!-- #ifndef MP-ALIPAY -->
		<canvas class="tki-qrcode-canvas" :canvas-id="cid" :style="{width:cpSize+'px',height:cpSize+'px'}" />
		<!-- #endif -->
		<!-- #ifdef MP-ALIPAY -->
		<canvas :id="cid" :width="cpSize" :height="cpSize" class="tki-qrcode-canvas" />
		<!-- #endif -->
		<image v-show="show" :src="result" :style="{width:cpSize+'rpx',height:cpSize+'rpx'}" />
	</view>
</template>

<script>
	import QRCode from "./qrcode.js"
	import {
		base64ToPath,
		pathToBase64
	} from '@/components/mmmm-image-tools/index.js'
	import permision from "@/components/wa-permission/permission.js"
	let qrcode
	export default {
		name: "tki-qrcode",
		props: {
			cid: {
				type: String,
				default: 'tki-qrcode-canvas'
			},
			size: {
				type: Number,
				default: 400
			},
			unit: {
				type: String,
				default: 'rpx'
			},
			show: {
				type: Boolean,
				default: true
			},
			val: {
				type: String,
				default: ''
			},
			background: {
				type: String,
				default: '#ffffff'
			},
			foreground: {
				type: String,
				default: '#000000'
			},
			pdground: {
				type: String,
				default: '#000000'
			},
			icon: {
				type: String,
				default: ''
			},
			iconSize: {
				type: Number,
				default: 80
			},
			lv: {
				type: Number,
				default: 3
			},
			onval: {
				type: Boolean,
				default: false
			},
			loadMake: {
				type: Boolean,
				default: false
			},
			usingComponents: {
				type: Boolean,
				default: true
			},
			showLoading: {
				type: Boolean,
				default: true
			},
			loadingText: {
				type: String,
				default: '二维码生成中'
			},
		},
		data() {
			return {
				result: '',
				src2: '',
			}
		},
		created() {
			uni.$on('baoc', () => {
				this._saveCode()
			})
		},
		methods: {
			_makeCode() {
				let that = this
				console.log(this.icon)
				if (!this._empty(this.val)) {
					qrcode = new QRCode({
						context: that, // 上下文环境
						canvasId: that.cid, // canvas-id
						usingComponents: that.usingComponents, // 是否是自定义组件
						showLoading: that.showLoading, // 是否显示loading
						loadingText: that.loadingText, // loading文字
						text: that.val, // 生成内容
						size: that.cpSize, // 二维码大小
						background: that.background, // 背景色
						foreground: that.foreground, // 前景色
						pdground: that.pdground, // 定位角点颜色
						correctLevel: that.lv, // 容错级别
						image: that.icon, // 二维码图标
						imageSize: that.iconSize, // 二维码图标大小
						cbResult: function(res) { // 生成二维码的回调
							that._result(res)
						},
					});
				} else {
					uni.showToast({
						title: '二维码内容不能为空',
						icon: 'none',
						duration: 2000
					});
				}
			},
			_clearCode() {
				this._result('')
				qrcode.clear()
			},
			_saveCode() {
				pathToBase64(this.result).then(base64 => {
					this.src2 = base64

					this.savePoster()
				}).catch(error => {
					console.log(error)

				})
			},
			async requestAndroidPermission(permisionID) {
				var result = await permision.requestAndroidPermission(permisionID)
				var strStatus
				if (result == 1) {
					strStatus = "已获得授权"
					console.log(666)
					this.saveImageToPhotosAlbum();
				} else if (result == 0) {
					strStatus = "未获得授权"
				} else {
					uni.showToast({
						title: "保存失败，请打开权限功能重试",
						icon: "none"
					});
				}
			},
			savePoster() {

				var isIos
				// #ifdef APP-PLUS
				isIos = (plus.os.name == "iOS")
				if (isIos) {
					this.saveImageToPhotosAlbum();
				} else {
					console.log(666)
					// this.saveImageToPhotosAlbum();
					this.requestAndroidPermission('android.permission.WRITE_EXTERNAL_STORAGE')
				}
				// #endif

				// #ifdef MP-WEIXIN
				uni.getSetting({ //获取用户的当前设置
					success: (res) => {
						console.log(res)
						if (res.authSetting['scope.writePhotosAlbum']) { //验证用户是否授权可以访问相册
							this.saveImageToPhotosAlbum();
						} else {
							uni.authorize({ //如果没有授权，向用户发起请求
								scope: 'scope.writePhotosAlbum',
								success: () => {
									this.saveImageToPhotosAlbum();
								},
								fail: () => {
									uni.showToast({
										title: "保存失败，请打开保存相册权限",
										icon: "none",
										duration: 3000,
									});
									uni.openSetting({ //调起客户端小程序设置界面,让用户开启访问相册
										success: (res2) => {
											console.log(res2)
										}
									});
								}
							})
						}
					}
				})
				// #endif
			},
			saveImageToPhotosAlbum() {
				uni.showLoading({
					title: '保存中...',
					mask: true
				})
				// #ifdef APP-PLUS
				uni.saveImageToPhotosAlbum({
					filePath: this.result,
					success: function() {
						uni.showToast({
							title: '图片保存成功',
							icon: 'none',
							duration: 2200
						});
					},
					fail: function(fail) {
						uni.showModal({
							content: '检测到您没打开获取信息功能权限，是否去设置打开？',
							confirmText: "确认",
							cancelText: '取消',
							success: (res2) => {
								if (res2.confirm) {
									permision.gotoAppPermissionSetting()
								} else {
									uni.showToast({
										title: "保存失败，请打开权限功能重试",
										icon: "none"
									});
								}
							}
						})
					}
				});
				// uni.downloadFile({
				// 	url: this.result,
				// 	success: function(res1) {
				// 		console.log(res1)
				// 		if (res1.statusCode) {


				// 		}
				// 	},
				// 	fail: function() {
				// 		console.log('fail')
				// 	}
				// })
				// #endif
				// #ifdef MP-WEIXIN
				let base64 = this.src2.replace(/^data:image\/\w+;base64,/, ""); //去掉data:image/png;base64,
				let filePath = wx.env.USER_DATA_PATH + '/ph_fit_qrcode.png';
				uni.getFileSystemManager().writeFile({
					filePath: filePath, //创建一个临时文件名
					data: base64, //写入的文本或二进制数据
					encoding: 'base64', //写入当前文件的字符编码
					success: res => {
						uni.saveImageToPhotosAlbum({
							filePath: filePath,
							success: function(res2) {
								uni.hideLoading();
								uni.showToast({
									title: '保存成功',
									icon: "none",
									duration: 1000
								})
							},
							fail: function(err) {
								uni.hideLoading();
								// console.log(err.errMsg);
							}
						})
					},
					fail: err => {
						uni.hideLoading();
						//console.log(err)
					}
				})
				// #endif
			},
			_result(res) {
				this.result = res;
				this.$emit('result', res)
			},
			_empty(v) {
				let tp = typeof v,
					rt = false;
				if (tp == "number" && String(v) == "") {
					rt = true
				} else if (tp == "undefined") {
					rt = true
				} else if (tp == "object") {
					if (JSON.stringify(v) == "{}" || JSON.stringify(v) == "[]" || v == null)
						rt = true
				} else if (tp == "string") {
					if (v == "undefined" || v == "null" || v == "{}" || v == "[]") rt = true
				} else if (tp == "function") {
					rt = false
				}
				return rt
			}
		},
		watch: {
			size: function(n, o) {
				if (n != o && !this._empty(n)) {
					this.cSize = n
					if (!this._empty(this.val)) {
						setTimeout(() => {
							this._makeCode()
						}, 100);
					}
				}
			},
			val: function(n, o) {
				if (this.onval) {
					if (n != o && !this._empty(n)) {
						setTimeout(() => {
							this._makeCode()
						}, 0);
					}
				}
			},
			background: function(n, o) {
				if (this.onval) {
					if (n != o && !this._empty(n)) {
						setTimeout(() => {
							this._makeCode()
						}, 0);
					}
				}
			},
			foreground: function(n, o) {
				if (this.onval) {
					if (n != o && !this._empty(n)) {
						setTimeout(() => {
							this._makeCode()
						}, 0);
					}
				}
			},
			pdground: function(n, o) {
				if (this.onval) {
					if (n != o && !this._empty(n)) {
						setTimeout(() => {
							this._makeCode()
						}, 0);
					}
				}
			},
			icon: function(n, o) {
				if (this.onval) {
					if (n != o && !this._empty(n)) {
						setTimeout(() => {
							this._makeCode()
						}, 0);
					}
				}
			}
		},
		computed: {
			cpSize() {
				if (this.unit == "upx") {
					return uni.upx2px(this.size)
				} else {
					return this.size
				}
			}
		},
		mounted: function() {
			if (this.loadMake) {
				if (!this._empty(this.val)) {
					setTimeout(() => {
						this._makeCode()
					}, 0);
				}
			}
		},
	}
</script>
<style>
	.tki-qrcode {
		position: relative;
	}

	.tki-qrcode-canvas {
		position: fixed;
		top: -99999upx;
		left: -99999upx;
		z-index: -99999;
	}
</style>
